package com.rr.frame.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;

public class InitRequestParameter {
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> initParameters(HttpServletRequest request){
		
		 Map<String,Object> paraMap = new HashMap<String, Object>();
		 try{
			 //request.setCharacterEncoding("UTF-8");
			 int size = request.getContentLength();
			 InputStream is = request.getInputStream();	
	         byte[] reqBodyBytes = readBytes(is, size);
	         String res = new String(reqBodyBytes);
	         System.out.println("res:" + res);
	         paraMap = JSON.parseObject(res, Map.class);
		 }catch (Exception e) {
			e.printStackTrace();
		}
		return paraMap;
	}
	
	public static final byte[] readBytes(InputStream is, int contentLen) {
	     if (contentLen > 0) {
	    	 int readLen = 0;
	         int readLengthThisTime = 0;
	         byte[] message = new byte[contentLen];
	         try {
	        	 while (readLen != contentLen) {
	        		 readLengthThisTime = is.read(message, readLen, contentLen - readLen);
	                 if (readLengthThisTime == -1) {// Should not happen.
	                	 break;
	                  }
	                 readLen += readLengthThisTime;
	             	}           
	        	 return message;     
	        	 
	             } catch (IOException e) {
	                     // Ignore
	                     // e.printStackTrace();
	             }
	     }
	     return new byte[] {};
	}
}
